package com.sky.task;

import com.alibaba.fastjson.JSON;
import com.hxc.pay.CommonPayTemplate;
import com.hxc.pay.wx.service.PaySuccessService;
import com.sky.mapper.user.OrderMapper;
import com.sky.pojo.Orders;
import com.sky.service.user.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

/**
 * @Description MyTask
 * @Author lyh
 * @Date 2024-10-13
 */
@Component
public class MyTask {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private CommonPayTemplate commonPayTemplate;
    @Autowired
    private PaySuccessService paySuccessService;
    @Scheduled(cron = "0 0/1 * * * ?")
    public void scanCancelOrders(){
        System.out.println("超时订单清理开始");
//        1.获取支付超时的订单（15分钟未支付）
        Calendar calendar=Calendar.getInstance();
        calendar.add(Calendar.MINUTE,-15);
        List<Orders> list=orderMapper.selectByStatusAndTime(Orders.PENDING_PAYMENT,calendar.getTime(),null);
        if(list!=null && list.size()>0){
            list.forEach(orders -> {
                //        2.调用微信的查单接口，确认支付状态是未支付
                String s = commonPayTemplate.queryOrder(orders.getNumber());
                    if(!s.equals("")) {
                        String trade_state = (String) JSON.parseObject(s, Map.class).get("trade_state");
                        if ("NOTPAY".equals(trade_state)) {
                            //        3.调用微信的关单接口，关闭订单
                            commonPayTemplate.close(orders.getNumber());
                            //        4.修改数据库订单的状态为取消支付
                            orderMapper.updateOrdersStatusById(Orders.CANCELLED_ORDER, orders.getId());
                        }
                    }
            });

        }
    }
    //@Scheduled(cron = "0/3 * * * * *")
    public void queryOrderTask(){
        //1.查询当下未支付的订单
        Calendar calendar=Calendar.getInstance();
        calendar.add(Calendar.MINUTE,-15);
        List<Orders> list=orderMapper.selectByStatusAndTime(Orders.PENDING_PAYMENT,null,calendar.getTime());
        if(list!=null&&list.size()>0){
            list.forEach(orders -> {
                //2.调用微信的查询接口，查询订单的支付状态
                String s = commonPayTemplate.queryOrder(orders.getNumber());
                String trade_state = (String) JSON.parseObject(s, Map.class).get("trade_state");
                if("SUCCESS".equals(trade_state)){
                    //3.如果是已支付，修改订单状态未已支付
                   /* orders.setPayStatus(Orders.PAID);
                    orders.setStatus(Orders.TO_BE_CONFIRMED);
                    orders.setCheckoutTime(LocalDateTime.now());
                    orderMapper.updatePaySuccess(orders);*/
                   paySuccessService.success(orders.getNumber());
                }
            });
        }
    }
}
